<template>
  <div class="music-app">
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="250px" class="app-sidebar">
        <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            @select="handleMenuSelect"
        >
          <el-menu-item index="songs">
            <el-icon>
              <Headset/>
            </el-icon>
            <span>所有歌曲</span>
          </el-menu-item>
          <el-menu-item index="playlists">
            <el-icon>
              <List/>
            </el-icon>
            <span>我的歌单</span>
          </el-menu-item>
          <el-menu-item index="history" v-if="isLoggedIn">
            <el-icon>
              <Clock/>
            </el-icon>
            <span>播放历史</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-main class="app-main">
        <!-- 播放器控制栏 -->
        <div class="player-controls">
          <div class="song-info">
            <el-image
                v-if="currentSong"
                :src="currentSong.cover"
                fit="cover"
                class="song-cover"
            ></el-image>
            <div v-else class="song-cover empty-cover">
              <el-icon>
                <Headset/>
              </el-icon>
            </div>

            <div class="song-meta">
              <h3 v-if="currentSong">{{ currentSong.title }}</h3>
              <h3 v-else class="no-song">未选择歌曲</h3>
              <p v-if="currentSong">{{ currentSong.artist }}</p>
              <p v-else class="no-song">请从列表中选择一首歌曲</p>
            </div>
          </div>

          <div class="control-buttons">
            <el-button circle @click="playPrev" :disabled="!hasPrevSong || !currentSong">
              <el-icon>
                <ArrowLeft/>
              </el-icon>
            </el-button>
            <el-button
                type="primary"
                circle
                @click="togglePlay"
                class="play-button"
                :disabled="!currentSong"
            >
              <el-icon v-if="!isPlaying">
                <VideoPlay/>
              </el-icon>
              <el-icon v-else>
                <VideoPause/>
              </el-icon>
            </el-button>
            <el-button circle @click="playNext" :disabled="!hasNextSong || !currentSong">
              <el-icon>
                <ArrowRight/>
              </el-icon>
            </el-button>
          </div>

          <div class="progress-container">
            <span class="time">{{ formatTime(currentTime) }}</span>
            <el-slider
                v-model="currentTime"
                :max="duration"
                :format-tooltip="formatTime"
                @change="seekTo"
                class="progress-slider"
                :disabled="!currentSong"
            ></el-slider>
            <span class="time">{{ formatTime(duration) }}</span>
          </div>

          <audio
              ref="audioPlayer"
              @timeupdate="updateTime"
              @ended="onSongEnded"
              @loadedmetadata="onLoadedMetadata"
          ></audio>
        </div>

        <!-- 内容区域 -->
        <div class="content-area">
          <el-skeleton :loading="songStore.isLoading" animated>
            <template #default>
              <!-- 歌曲列表 -->
              <div v-if="activeMenu === 'songs'">
                <h2>所有歌曲</h2>
                <el-table
                    :data="songStore.songs"
                    style="width: 100%"
                    @row-click="playSong"
                    :row-class-name="tableRowClassName"
                >
                  <el-table-column prop="title" label="歌曲" width="180"></el-table-column>
                  <el-table-column prop="artist" label="歌手"></el-table-column>
                  <el-table-column prop="duration" label="时长" :formatter="formatDuration"></el-table-column>
                </el-table>
              </div>

              <!-- 歌单列表 -->
              <div v-if="activeMenu === 'playlists'">
                <h2>我的歌单</h2>
                <div class="playlist-grid">
                  <el-card
                      v-for="playlist in playlistStore.playlists"
                      :key="playlist.id"
                      shadow="hover"
                      @click="viewPlaylist(playlist.id)"
                      class="playlist-card"
                  >
                    <el-image
                        :src="playlist.cover || '/default-playlist-cover.jpg'"
                        fit="cover"
                        class="playlist-cover"
                    ></el-image>
                    <div class="playlist-info">
                      <h3>{{ playlist.name }}</h3>
                      <p>{{ playlist.songs?.length || 0 }} 首歌曲</p>
                    </div>
                  </el-card>
                </div>
              </div>

              <!-- 播放历史 -->
              <div v-if="activeMenu === 'history' && isLoggedIn">
                <h2>播放历史</h2>
                <el-table
                    :data="historyStore.playHistory"
                    style="width: 100%"
                    @row-click="playHistorySong"
                >
                  <el-table-column label="歌曲">
                    <template #default="{ row }">
                      <div class="history-song">
                        <el-image
                            :src="row.song.cover"
                            fit="cover"
                            class="history-cover"
                        ></el-image>
                        <div class="history-info">
                          <h4>{{ row.song.title }}</h4>
                          <p>{{ row.song.artist }}</p>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="play_count" label="播放次数" width="120"></el-table-column>
                  <el-table-column prop="last_played" label="最后播放" width="180">
                    <template #default="{ row }">
                      {{ formatDate(row.last_played) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-skeleton>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue'
import {storeToRefs} from 'pinia'
import {
  Headset, List, Clock,
  ArrowLeft, ArrowRight, VideoPlay, VideoPause
} from '@element-plus/icons-vue'
import {useSongStore, usePlaylistStore, useSongHistoryStore} from '@/stores/music.js'
import {ElMessage} from "element-plus";

// 状态管理
const songStore = useSongStore()
const playlistStore = usePlaylistStore()
const historyStore = useSongHistoryStore()

// 从store解构需要的状态
const {songs, currentSong} = storeToRefs(songStore)
const {playlists} = storeToRefs(playlistStore)
const {playHistory} = storeToRefs(historyStore)

// 组件状态
const activeMenu = ref('songs')
const audioPlayer = ref(null)
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const isLoggedIn = ref(false) // 根据实际登录状态设置

// 计算属性
const hasPrevSong = computed(() => {
  if (!currentSong.value) return false
  const currentIndex = songStore.songs.findIndex(song => song.id === currentSong.value.id)
  return currentIndex > 0
})

const hasNextSong = computed(() => {
  if (!currentSong.value) return false
  const currentIndex = songStore.songs.findIndex(song => song.id === currentSong.value.id)
  return currentIndex < songStore.songs.length - 1
})

// 初始化加载数据
onMounted(() => {
  songStore.fetchAllSongs()
  playlistStore.fetchAllPlaylists()
  if (isLoggedIn.value) {
    historyStore.fetchPlayHistory()
  }
})

// 格式化时间显示
const formatTime = (seconds) => {
  if (isNaN(seconds)) return '00:00'
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 格式化表格中的时长
const formatDuration = (row, column, cellValue) => {
  return formatTime(cellValue)
}

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

// 播放歌曲
const playSong = async (song) => {
  // 多层防御性检查
  if (!audioPlayer.value) {
    ElMessage.warning('播放器初始化失败，请刷新页面')
    return
  }

  if (!song || !song.audio) {
    ElMessage.warning('无效的歌曲数据')
    return
  }

  try {
    // 暂停当前播放
    if (isPlaying.value) {
      audioPlayer.value.pause()
    }
    // 设置新歌曲
    songStore.setCurrentSong(song)
    audioPlayer.value.src = song.audio

    // 重置播放进度
    currentTime.value = 0

    // 等待音频准备就绪
    await new Promise((resolve, reject) => {
      let timeoutId
      const cleanup = () => {
        clearTimeout(timeoutId)
        audioPlayer.value.oncanplay = null
        audioPlayer.value.onerror = null
      }
      const onCanPlay = () => {
        cleanup()
        resolve(true)
      }

      const onError = () => {
        cleanup()
        reject(new Error('音频加载失败'))
      }

      timeoutId = setTimeout(() => {

        cleanup()
        reject(new Error('音频加载超时'))
      }, 10000)

      // **顺序非常重要**
      audioPlayer.value.oncanplay = onCanPlay
      audioPlayer.value.onerror = onError

      // 1. 设置新 src
      audioPlayer.value.src = song.audio

      // 2. 调用 load（可选，看浏览器，建议保留）
      audioPlayer.value.load()
    })


    // 开始播放
    await audioPlayer.value.play()
    isPlaying.value = true

    // 上报播放记录
    if (isLoggedIn.value) {
      try {
        await historyStore.reportPlay(song.id)
      } catch (reportError) {
      }
    }
  } catch (error) {

    isPlaying.value = false
    ElMessage.error(`播放失败: ${error.message}`)

    // 尝试恢复播放状态
    if (currentSong.value && currentSong.value.audio) {
      audioPlayer.value.src = currentSong.value.audio
    }
  }
}

// 播放历史中的歌曲
const playHistorySong = (historyItem) => {
  playSong(historyItem.song)
}

// 切换播放/暂停
const togglePlay = () => {
  if (!currentSong.value) {
    if (songStore.songs.length > 0) {
      playSong(songStore.songs[0])
    }
    return
  }

  if (isPlaying.value) {
    audioPlayer.value.pause()
  } else {
    audioPlayer.value.play()
  }
  isPlaying.value = !isPlaying.value
}

// 播放下一首
const playNext = () => {
  if (!currentSong.value) {
    if (songStore.songs.length > 0) {
      playSong(songStore.songs[0])
    }
    return
  }

  const currentIndex = songStore.songs.findIndex(song => song.id === currentSong.value.id)
  const nextIndex = (currentIndex + 1) % songStore.songs.length
  playSong(songStore.songs[nextIndex])
}

// 播放上一首
const playPrev = () => {
  if (!currentSong.value) {
    if (songStore.songs.length > 0) {
      playSong(songStore.songs[0])
    }
    return
  }

  const currentIndex = songStore.songs.findIndex(song => song.id === currentSong.value.id)
  const prevIndex = (currentIndex - 1 + songStore.songs.length) % songStore.songs.length
  playSong(songStore.songs[prevIndex])
}

// 更新当前播放时间
const updateTime = () => {
  currentTime.value = audioPlayer.value.currentTime || 0
}

// 歌曲结束处理
const onSongEnded = () => {
  playNext()
}

// 加载元数据
const onLoadedMetadata = () => {
  duration.value = audioPlayer.value.duration
}

// 跳转到指定时间
const seekTo = (value) => {
  audioPlayer.value.currentTime = value
}

// 查看歌单详情
const viewPlaylist = (id) => {
  playlistStore.fetchPlaylistDetail(id)
  // 这里可以跳转到歌单详情页或显示模态框
  // console.log('View playlist:', id)
}

// 菜单选择
const handleMenuSelect = (index) => {
  activeMenu.value = index
}

// 表格行类名
const tableRowClassName = ({row}) => {
  return currentSong.value && currentSong.value.id === row.id ? 'current-song-row' : ''
}
</script>

<style scoped>
.music-app {
  height: 100vh;
  display: flex;
}

.app-sidebar {
  background-color: #f5f7fa;
  border-right: 1px solid #e6e6e6;
}

.sidebar-menu {
  border-right: none;
  height: 100%;
}

.app-main {
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.player-controls {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.song-info {
  display: flex;
  align-items: center;
}

.song-cover {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 15px;
}

.song-meta h3 {
  margin: 0;
  font-size: 16px;
}

.song-meta p {
  margin: 5px 0 0;
  color: #666;
  font-size: 14px;
}

.control-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.play-button {
  width: 50px;
  height: 50px;
}

.progress-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-slider {
  flex-grow: 1;
}

.time {
  font-size: 12px;
  color: #666;
  min-width: 40px;
  text-align: center;
}

.content-area {
  flex-grow: 1;
}

.playlist-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.playlist-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.playlist-card:hover {
  transform: translateY(-5px);
}

.playlist-cover {
  width: 100%;
  height: 120px;
  border-radius: 4px;
}

.playlist-info {
  padding: 10px;
}

.playlist-info h3 {
  margin: 0;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.playlist-info p {
  margin: 5px 0 0;
  color: #666;
  font-size: 14px;
}

.history-song {
  display: flex;
  align-items: center;
}

.history-cover {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 10px;
}

.history-info h4 {
  margin: 0;
  font-size: 14px;
}

.history-info p {
  margin: 2px 0 0;
  color: #666;
  font-size: 12px;
}

:deep(.current-song-row) {
  background-color: #f0f7ff;
}
</style>